﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.AutoMapper;
using FwProject.Authorization.Users;
using FwProject.Com;
using FwProject.Commodity.Dto;
using FwProject.Configuration;
using FwProject.Web.ShopCore.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Abp.UI;
namespace FwProject.Controllers
{
    [Route("api/[controller]/[action]")]
    [AbpAuthorize]
    public class AppCreviewsController : FwProjectControllerBase
    {
        private readonly IHostingEnvironment env;
        private readonly IConfigurationRoot _appConfiguration;
        private readonly ICommodityReviewsAppService _commodityReviewsAppService;
        public AppCreviewsController(IHostingEnvironment _env, ICommodityReviewsAppService commodityReviewsAppService)
        {
            env = _env;
            _appConfiguration = _env.GetAppConfiguration();
            _commodityReviewsAppService = commodityReviewsAppService;
        }
        /// <summary>
        /// 添加评论
        /// </summary>
        /// <param name="input"></param>
        /// <param name="image"></param>
        /// <returns></returns>
        [HttpPost]
        public async  Task<IActionResult> AddCreviews(CreviewsModel inputmodel, IFormCollection image)
        {
            Logger.Debug("测试上传");

            var model = new User();
            string path = string.Empty;
          
            var files = image.Files;
            if (files == null || files.Count() <= 0)
            {
                throw new  UserFriendlyException("请上传图片");
            }
            //格式限制
            var allowType = new string[] { "image/jpg", "image/png", "image/jpeg", };

            CommodityReviewsInput input = inputmodel.MapTo<CommodityReviewsInput>();

            input.CommodityReviewsListImage = new List<CommodityReviewsImageInput>();
            if (files.Any(c => allowType.Contains(c.ContentType)))
            {
                try
                {
                    if (files.Sum(c => c.Length) <= 1024 * 1024 * 4)
                    {
                        foreach (var item in files)
                        {
                            var file = item;
                            string strpath = DateTime.Now.ToString("yyyyMMddHHmmss")+Guid.NewGuid() + Path.GetExtension(file.FileName);// Path.Combine("UploadCommodityReviews", );
                            //foreach (var file in files)
                            //{
                            //  string strpath = Path.Combine("Upload", DateTime.Now.ToString("MMddHHmmss") + file.FileName);
                            path = Path.Combine(env.WebRootPath, strpath);
                            var tempPath = Path.Combine(env.WebRootPath, "UploadCommodityReviews");
                            if (!Directory.Exists(tempPath))
                                Directory.CreateDirectory(tempPath);

                            Logger.Debug($"{tempPath}======={env.WebRootPath}");
                            Logger.Debug(path);

                          
                            string FileServicePath = _appConfiguration["FileServicePath:CommodityReviews:SavaFilePath"].ToString();
                            if (!Directory.Exists(FileServicePath))
                                Directory.CreateDirectory(FileServicePath);

                            using (var stream = new FileStream(Path.Combine(FileServicePath, strpath), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                await file.CopyToAsync(stream);
                            }
                            CommodityReviewsImageInput img = new CommodityReviewsImageInput();
                            img.Productid = input.Productid;
                            img.ImagePath =$"{_appConfiguration["FileServicePath:CommodityReviews:Virtual"].ToString()}{strpath}" ;
                            input.CommodityReviewsListImage.Add(img);
                        }

                      await  _commodityReviewsAppService.CreateCommodityReviews(input);
                    }
                    else
                    {
                        throw new UserFriendlyException("图片过大限制4M");
                       
                    }
                }
                catch (Exception exe)
                {
                  
                    Logger.Error(exe.ToString());
                    return Json(exe.ToString());
                }
               
                
            }
            else
            {
                throw new UserFriendlyException("图片格式错误");
            }
            return Json("");
        }
    }
}
